﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using UserInfo;
using Product;
using Base;
public partial class _register : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (CheckCookies())
        {
            Response.Redirect("../Error.aspx?err=1");
            return;
        }
        if (!IsPostBack)
        {
            if (bind())
            {
                IndustryBind();
                isShow();
            }
            this.bt.Text = Common.GetBottom(bt.Text);
            this.dl.Text = Base.Common.GetBottom(this.dl.Text);
        }
    }

    private void isShow()
    {
        Solely.UserRegistr set = Solely.UserRegistr.GateItem();

        //是否启用验证码
        if (set.isCode)
        {
            this.trCode.Visible = true;
            this.ViewState["isCode"] = "1";
        }
        else
        {
            this.trCode.Visible = false;
            this.ViewState["isCode"] = "0";
        }
        //是否启用验证问题
        if (set.isQuestion)
        {
            this.ViewState["isQuestion"] = "1";
            string[] strQuestrion;
            string[] strAnswer;
            if (set.Question.Contains("!"))
            {

                strQuestrion = set.Question.Split('!');  //分解问题存入数组
                strAnswer = set.Answer.Split('!');
                Random randObj = new Random();
                int intRandom = randObj.Next(0, 50);
                this.divAnswer.InnerText = strQuestrion[intRandom % strQuestrion.Length] + " " + strAnswer[intRandom % strQuestrion.Length];
                this.ViewState["Answer"] = strAnswer[intRandom % strQuestrion.Length];
            }
            else
            {
                this.divAnswer.InnerText = set.Question + " ? ";
                this.ViewState["Answer"] = set.Answer;
                return;
            }
        }
        else
        {
            this.ViewState["isQuestion"] = "0";
            this.trQuestion.Visible = false;
        }
    }

    private bool bind()
    {
        try
        {
            string IP = Base.GetRequest.GetIP();
            int outReturn = 0;
            int intIP = Solely.UserRegistr.CheckIP(IP);
            Solely.UserRegistr set = Solely.UserRegistr.GateItem();
            this.ViewState["intGradeID"] = set.VipGrade;
            if (!set.isRegister)   //是否允许注册
            {
                Response.Redirect("../Error.aspx?err=0");
                return false;
            }
            else
            {
                if (outReturn == -1)  //IP是否允许注册
                {
                    ShowMessage("您的IP在此段时间已经注册过请过会儿在注册", Config.WebURL);
                    return false;
                }
                else
                {
                    ViewState.Add("BannedUser", set.BannedUser);
                    ViewState.Add("BreakTime", set.MinTimeRegister);
                    ViewState.Add("Minimum", set.Minimum);
                    ViewState.Add("Longest", set.Longest);
                    this.HidminName.Value = set.Minimum.ToString();
                    this.HidmaxName.Value = set.Longest.ToString();

                    if (set.OnlyUser_Email) //是否一个Email只能注册一个帐号
                    {
                        this.hidEmail.Value = "1";
                    }
                    return true;
                }
            }
        }
        catch (Exception e)
        {
            ShowMessage(e.Message);
        }
        return true;
    }

    /// <summary>
    /// 所属行业
    /// </summary>
    private void IndustryBind()
    {
        //IIndustryType II = new RIndustryType();
        //DataTable db = II.GetDataTable(0);
        //dropIndustry.DataSource = db.DefaultView;
        //dropIndustry.DataTextField = "Type";
        //dropIndustry.DataValueField = "ID";
        //dropIndustry.DataBind();

    }

    /// <summary>
    /// 注册信息提交
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnServer_Click(object sender, EventArgs e)
    {
        string msgText = "";
        string code = this.yangzheng.Text;
        string testString = this.txtLoginName.Text;
        //验证码
        if (this.ViewState["isCode"].ToString() == "1")
        {
            if (!CheckCode(code))   //验证码检测
            {
                lbl_yangzheng.InnerText = "验证码错误";
                this.yangzheng.Focus();
                return;
            }
        }

        //验证答案
        if (this.ViewState["isQuestion"].ToString() == "1")
        {
            if (!this.txtQuestion.Text.Equals(this.ViewState["Answer"].ToString()))
            {
                ShowMessage("验证问题不正确！");
                return;
            }
        }
        int min = 4;
        int max = 12;
        min = int.Parse(this.ViewState["Minimum"].ToString());
        max = int.Parse(this.ViewState["Longest"].ToString());
        if ((testString.Length < min) || (testString.Length > max))  //(Base.Common.IsIncludeChineseCode(this.txtLoginName.Text.Trim()) ||
        {
            lbl_txtLoginName.InnerText = min + "～" + max + "位之间";
            return;
            //msgText = min + "～" + max + "位之间";
        }
        if (!this.txtPassword.Text.Trim().Equals(this.txtOldPassword.Text))
        {
            lbl_txtOldPassword.InnerText = "两次密码输入不一致";
            return;
            // msgText = msgText + "<br/>两次密码输入不一致";
        }
        string noUser = "";
        noUser = this.ViewState["BannedUser"].ToString();
        if (noUser.IndexOf(this.txtLoginName.Text) > 0)    //会员名检测
        {
            lbl_txtLoginName.InnerText = "不允许注册的会员名";
            return;
        }
        if (msgText != "")
        {
            lbl_txtLoginName.InnerText = msgText;
            return;
        }
        else
        {
            SaveUserInfo();
        }

    }

    /// <summary>
    /// 保存会员提交的信息
    /// </summary>
    private void SaveUserInfo()
    {
        string strError = "您提交的信息有以下错误，请重新提交!";
        IUserInfo RUser = new RUserInfo();
        TUserInfo TUser = new TUserInfo();
        try
        {
            string myValue = "";
            if (Request.Form["SortB"] != null && Request.Form["SortB"] != "")
                myValue += Request.Form["SortB"];
            if (Request.Form["SortM"] != null && Request.Form["SortM"] != "")
                myValue += "," + Request.Form["SortM"];
            if (Request.Form["SortS"] != null && Request.Form["SortS"] != "")
                myValue += "," + Request.Form["SortS"];
            TUser.LoginName = this.txtLoginName.Text;
            string Md5Pawd = "";
            if (GetRequest.IsIncludeChineseCode(this.txtPassword.Text))
            {
                lbl_txtOldPassword.InnerText = "密码不能包行中文字符！";
                return;
            }
            else
            {
                Md5Pawd = Common.Encryption(this.txtPassword.Text);
            }
            TUser.Password = Md5Pawd;
            if (!GetRequest.isMail(this.txtEmail.Text))
            {
                lbl_txtEmail.InnerText = "邮箱格式不正确！";
                return;
            }
            else
            {
                TUser.Email = this.txtEmail.Text;
            }

            TUser.Question = this.dropQuestion.SelectedValue;
            if (GetRequest.CheckBadWord(txtAnswer.Text))
            {
                lbl_txtAnswer.InnerText = "您输入的问题答案中有非法字符！";
                return;
            }
            else
            {
                TUser.Answer = this.txtAnswer.Text;
            }

            TUser.LinkName = this.txtLinkName.Text;
            TUser.Sex = this.radlSex.SelectedValue.ToString();
            TUser.Department = this.txtDepartment.Text;
            TUser.Position = this.txtPosition.Text;
            TUser.Tel_International = this.txtTel_International.Text;
            TUser.Tel_DistrictNumber = this.txtTel_DistrictNumber.Text;
            TUser.Tel_Telephone = this.txtTel_Telephone.Text;
            TUser.Tel_Ext = this.txtTel_Ext.Text;
            TUser.Fax_International = this.txtFax_International.Text;
            TUser.Fax_DistrictNumber = this.txtFax_DistrictNumber.Text;
            TUser.Fax_Telephone = this.txtFax_Telephone.Text;
            TUser.Fax_Ext = this.txtFax_Ext.Text;
            TUser.MobilePhone = this.txtMobilePhone.Text;
            TUser.BusinessModel = this.BusinessModel.Text;
            if ((!GetRequest.isNum(this.txtQQ.Text)) && (txtQQ.Text.Trim() != ""))
            {
                lbl_QQ.InnerText = "您输入的QQ格式不正确！";
                return;
            }
            else
            {
                TUser.QQ = this.txtQQ.Text;
            }
            TUser.MSN = this.txtMSN.Text;
            TUser.CompanyNature = this.radlCompanyNature.SelectedValue;
            TUser.CompanyName = this.txtCompanyName.Text;
            if (GetRequest.CheckBadWord(this.txtDealinAdd.Text))
            {
                lbl_txtDealinAdd.InnerText = "您输入的经营地址中有非法字符！";
                return;
            }
            else
            {
                TUser.DealinAdd = this.txtDealinAdd.Text;
            }

            TUser.Industry = myValue;
            TUser.RegDate = Convert.ToDateTime(DateTime.Now.Date);
            TUser.Country = Request.Form["country"];
            TUser.Province = Request.Form["province"];
            TUser.City = Request.Form["city"];
            TUser.Area = Request.Form["county"];
            TUser.GradeID = Convert.ToInt32(this.ViewState["intGradeID"]);
            RUser.Insert(TUser);
        }
        catch
        {
        }
        try
        {
            //读取指定节点下的value值
            string strFlag = Base.XMLProcess.Read("xml/EmailFlag.xml", "/Item/flag/mode[@type='userRegister']", "value");
            if (strFlag == "")
                strFlag = "us_register";
            if (Base.Common.isMail(txtEmail.Text.Trim()))
                nspBase.Core.clsEmail.SendMail(strFlag, txtEmail.Text.Trim());
        }
        catch
        {
            //lbl_txtEmail.InnerText = "邮件发送失败!";
            //return;
        }
        Solely.UserRegistr set = Solely.UserRegistr.GateItem();
        if (set.ManageRegister)   //是否需要审核
        {
            ShowMessage("注册成功!请等待管理员审核!", "../Default.aspx");
        }
        else
        {
            try
            {
                DataSet tableset = RUser.GetDataTable(TUser.LoginName, TUser.Password);
                GetRequest.SetCookie("LoginName", tableset.Tables[0].Rows[0]["LoginName"].ToString());
                GetRequest.SetCookie("CheckInfo", tableset.Tables[0].Rows[0]["Password"].ToString());
                GetRequest.SetCookie("UserID", tableset.Tables[0].Rows[0]["UserID"].ToString());
                GetRequest.SetCookie("GradeID", tableset.Tables[0].Rows[0]["GradeID"].ToString());
                GetRequest.SetCookie("CompanyName", tableset.Tables[0].Rows[0]["CompanyName"].ToString());
                Response.Redirect("Success.aspx");
            }
            catch
            {
                ShowMessage("登陆失败!");
            }
        }

    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/member/Index.aspx");
    }


}
